package com.zking.myservlet.product;

import com.sun.corba.se.impl.oa.toa.TOA;
import com.zking.dao.ProductDao;
import com.zking.entity.Product;
import com.zking.util.Tools;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Base64;
import java.util.List;

@WebServlet("/manage/ProductList")
public class ProductList extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html");
        resp.setCharacterEncoding("UTF-8");

        int index = 1;
        int pageSize = 2;
        String tmp = req.getParameter("pageIndex");
        if(tmp!=null)
        {
            index = Integer.parseInt(tmp);
        }

        List<Product> list = ProductDao.selectProductByPage(index, pageSize, 0);
        List<String> imageBytes = new ArrayList<>(); // 用来存储图像。因为需要通过Base64编码，所以用单独的数组存储

        // 获取图像，并进行编码
        for (Product product : list) {
            byte[] tmpBytes = product.getEp_image_bytes();
            if(tmpBytes!=null){
                imageBytes.add(Tools.bytesToString(tmpBytes));
            }else{
                imageBytes.add("");
            }
        }

        int maxPage = ProductDao.getMaxPage(pageSize, 0);
        index = Math.max(1, index);
        index = Math.min(index, maxPage);

        req.setAttribute("list", list);
        req.setAttribute("images", imageBytes);
        req.setAttribute("maxPage", maxPage);
        req.setAttribute("pageIndex", index);
        req.getRequestDispatcher("product.jsp").forward(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
